package com.dks.repository.impl.student;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dks.dto.BaseIdRequestDto;
import com.dks.dto.student.*;
import com.dks.enumeration.AppointmentType;
import com.dks.enumeration.DictionaryType;
import com.dks.exception.BaseException;
import com.dks.mapper.*;
import com.dks.models.Parent;
import com.dks.models.QsClass;
import com.dks.models.publicCompoment.PublicDictionary;
import com.dks.models.student.AppointmentClassStrategy;
import com.dks.models.student.PositionWait;
import com.dks.repository.IAppointmentClassRepository;
import com.dks.repository.IClassHourUseRepository;
import com.dks.result.*;
import com.dks.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.lang.Collections;

@Repository
public class AppointmentClassRepository implements IAppointmentClassRepository {

    @Autowired
    private AppointmentClassStrategyMapper appointmentClassStrategyMapper;
    @Autowired
    private QsClassMapper qsClassMapper;
    @Autowired
    private PublicDictionaryMapper publicDictionaryMapper;
    @Autowired
    private IClassHourUseRepository classHourUseRepository;
    @Autowired
    private PositionWaitMapper positionWaitMapper;
    @Autowired
    private ParentMapper parentMapper;


    /**
     * 约课攻略-列表
     * @author evan
     */
    @Override
    public ResultModel<PageInfo<AppointmentClassStrategy>> getStrategyList(Integer pageNum, Integer pageSize) {
        Page p= PageHelper.startPage(pageNum, pageSize);
        List<AppointmentClassStrategy> list = appointmentClassStrategyMapper.getList();
        PageInfo<AppointmentClassStrategy> pageInfo = new PageInfo<>(pageNum,pageSize,p.getTotal(),p.getPages(),list);
        return Result.makeResult(ResultInfo.SUCCESS, pageInfo);
    }

    /**
     * 约课攻略-详情
     * @author evan
     */
    @Override
    public ResultModel<AppointmentClassStrategy> getStrategy(Integer id) {
        AppointmentClassStrategy appointmentClassStrategy = appointmentClassStrategyMapper.select(id);
        return Result.makeResult(ResultInfo.SUCCESS, appointmentClassStrategy);
    }

    /**
     * 固定位-约课
     * @author evan
     */
    @Transactional
    @Override
    public ResultModel<Boolean> fixed(AppointClassDto appointClassDto) throws BaseException {
        //查询家长信息
        Parent parent = parentMapper.getByUserId(appointClassDto.getUserId());
        if (parent == null){
            return Result.makeResult(ResultInfo.ERR_PARENT_001);
        }
        //1.班级查询
        QsClass qsClass = qsClassMapper.select(appointClassDto.getQsClassId());
        if (qsClass == null){
            return Result.makeResult(ResultInfo.ERR_CLASS_001);
        }
        //2.根据课程系列id查询从当前日期之后的所有班级
        List<QsClassCapacityDto> qsClassCapacityDtoList = qsClassMapper.getCountBySeriesId(qsClass.getQsClassSeriesId(), qsClass.getLessonStartTime());
        //3.判断位置是否够用
        for (QsClassCapacityDto qsClassCapacityDto : qsClassCapacityDtoList) {
            if (qsClassCapacityDto.getCapacityNum() >= qsClassCapacityDto.getCapacity()){
                return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_003);
            }
        }
        classHourUseRepository.useAppointClass(qsClassCapacityDtoList, appointClassDto.getUserId(), appointClassDto.getStudentId(), parent.getId(), AppointmentType.FIXED);
        return Result.makeResult(ResultInfo.SUCCESS);
    }

    /**
     * 临时位-约课
     * @author evan
     */
    @Override
    public ResultModel<Boolean> temporary(AppointClassDto appointClassDto) throws BaseException {
        //查询家长信息
        Parent parent = parentMapper.getByUserId(appointClassDto.getUserId());
        if (parent == null){
            return Result.makeResult(ResultInfo.ERR_PARENT_001);
        }
        //1.班级查询
        QsClassCapacityDto qsClassCapacityDto = qsClassMapper.getCountByClassId(appointClassDto.getQsClassId(), LocalDateTime.now());
        if (qsClassCapacityDto == null){
            return Result.makeResult(ResultInfo.ERR_CLASS_001);
        }
        //判断位置是否够用
        if (qsClassCapacityDto.getCapacityNum() >= qsClassCapacityDto.getCapacity()){
            return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_003);
        }
        classHourUseRepository.useAppointClass(Arrays.asList(qsClassCapacityDto), appointClassDto.getUserId(), appointClassDto.getStudentId(), parent.getId(), AppointmentType.TEMPORARY);
        return Result.makeResult(ResultInfo.SUCCESS);
    }

    /**
     * 体验位-约课
     * @author evan
     */
    @Override
    public ResultModel<Boolean> experience(AppointClassDto appointClassDto) {
        return null;
    }

    /**
     * 固定位-等位
     * @author evan
     */
    @Override
    public ResultModel<Boolean> fixedWait(PositionWaitDto positionWaitDto) throws BaseException {
        //查询排队信息
        List<PositionWait> userPositionWait = positionWaitMapper.getListByClassSeriesId(positionWaitDto.getQsClassSeriesId(), positionWaitDto.getStudentId());
        if (!Collections.isEmpty(userPositionWait)){
            return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_009);
        }
        //查询家长信息
        Parent parent = parentMapper.getByUserId(positionWaitDto.getUserId());
        if (parent == null){
            return Result.makeResult(ResultInfo.ERR_PARENT_001);
        }
        //固定位等位人数限制
        List<PublicDictionary> fixedWaitNumList = publicDictionaryMapper.getByType(DictionaryType.FIXED_WAIT_NUM.name());
        Integer fixedWaitNum = IntegerUtils.String2Integer(Collections.isEmpty(fixedWaitNumList)? null : fixedWaitNumList.get(0).getDictData());
        //等位人数查询
        List<PositionWait> positionWaitList = positionWaitMapper.getListByClassSeriesId(positionWaitDto.getQsClassSeriesId(), null);
        if (!Collections.isEmpty(positionWaitList)){
            if (fixedWaitNum != null && fixedWaitNum <= positionWaitList.size()){
                return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_004);
            }
        }
        //1.班级查询
        List<QsClassCapacityDto> qsClassCapacityDtoList = qsClassMapper.getCountBySeriesId(positionWaitDto.getQsClassSeriesId(), LocalDateTime.now());
        if (Collections.isEmpty(qsClassCapacityDtoList)){
            return Result.makeResult(ResultInfo.ERR_CLASS_001);
        }
        //TODO 测试
//        classHourUseRepository.useWaitClass(qsClassCapacityDtoList, positionWaitDto.getUserId(), positionWaitDto.getStudentId(), parent.getId());
        //增加等位数据
        PositionWait positionWait = new PositionWait();
        positionWait.setStudentId(positionWaitDto.getStudentId());
        positionWait.setParentId(parent.getId());
        positionWait.setQsClassSeriesId(positionWaitDto.getQsClassSeriesId());
        positionWait.setCreateUserId(positionWaitDto.getUserId());
        positionWait.setFixedWaitNum(fixedWaitNum);
        int i = positionWaitMapper.insert(positionWait);
        if (i > 0){
            return Result.makeResult(ResultInfo.SUCCESS);
        }else{
            throw new BaseException(ResultInfo.ERR_APPOINT_CLASS_008);
        }
    }

    /**
     * 固定位-取消等位
     * @author evan
     */
    @Override
    public ResultModel<Boolean> fiexedWaitCancel(BaseIdRequestDto baseIdRequestDto) throws BaseException {
        //查询排队信息
        PositionWait positionWait = positionWaitMapper.select(baseIdRequestDto.getId());
        if (positionWait == null){
            return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_005);
        }
        //取消等位次数限制
        List<PublicDictionary> fixedWaitCancelLimitList = publicDictionaryMapper.getByType(DictionaryType.FIXED_WAIT_CANCEL_LIMIT.name());
        Integer fixedWaitCancelLimit = IntegerUtils.String2Integer(Collections.isEmpty(fixedWaitCancelLimitList)? null : fixedWaitCancelLimitList.get(0).getDictData());
        if (fixedWaitCancelLimit != null){
            //查询本周的取消次数
            int cancelNum = positionWaitMapper.getCancelNum(baseIdRequestDto.getUserId(), TimeUtils.getStartTimeOfWeek(), TimeUtils.getEndTimeOfWeek());
            if (cancelNum >= fixedWaitCancelLimit){
                return Result.makeResult(ResultInfo.ERR_APPOINT_CLASS_006);
            }
        }
//        classHourUseRepository.waitCancel(Arrays.asList(positionWait), baseIdRequestDto.getUserId(), fixedWaitCancelLimit);
        //取消等位
        int i = positionWaitMapper.remove(baseIdRequestDto.getId());
        if (i > 0){
            return Result.makeResult(ResultInfo.SUCCESS);
        }else{
            throw new BaseException(ResultInfo.ERR_APPOINT_CLASS_007);
        }

    }

    /***
     * 冻结课时
     * @author evan
     */
//    public void frozenClassHour(List<UserClassHourPackage> userClassHourPackageList, Integer classHour) throws BaseException {
//         //用户课时包排序 剩余有效期最短的课时包 如果相同 那就从购买时间最早
//         userClassHourPackageList.sort((userClassHourPackage1, userClassHourPackage2)->{
//             if (userClassHourPackage1.getExpireTime().isBefore(userClassHourPackage2.getExpireTime())){
//                 return 1;
//             }else if (userClassHourPackage1.getExpireTime().isAfter(userClassHourPackage2.getExpireTime())){
//                 return -1;
//             }else if (userClassHourPackage1.getExpireTime().isEqual(userClassHourPackage2.getExpireTime())){
//                 if (userClassHourPackage1.getGmtCreateTime().isBefore(userClassHourPackage2.getGmtCreateTime())){
//                     return 1;
//                 }else if (userClassHourPackage1.getGmtCreateTime().isAfter(userClassHourPackage2.getGmtCreateTime())){
//                     return -1;
//                 }else{
//                     return 0;
//                 }
//             }else{
//                 return 0;
//             }
//         });
//        //冻结课时包
//        for (UserClassHourPackage userClassHourPackage : userClassHourPackageList){
//            //课时包剩余可用课时数
//            int lastClassHour = userClassHourPackage.getAvailableClassHourCount() - userClassHourPackage.getFrozenClassHourCount() - userClassHourPackage.getUsedClassHourCount();
//            while (classHour > 0){
//                if (classHour >= lastClassHour){
//                    classHour -= lastClassHour;
//                    //当前课时包不够用
//                    int i = userClassHourPackageMapper.frozenClassHour(userClassHourPackage.getId(), lastClassHour);
//                    if (i <= 0){
//                        throw new BaseException(ResultInfo.ERR_APPOINT_CLASS_001);
//                    }
//                }else{
//                    classHour = 0;
//                    int i = userClassHourPackageMapper.frozenClassHour(userClassHourPackage.getId(), classHour);
//                    if (i <= 0){
//                        throw new BaseException(ResultInfo.ERR_APPOINT_CLASS_001);
//                    }
//                }
//            }
//        }
//
//    }
}
